// 游戏配置
const CONFIG = {
    CANVAS_WIDTH: 800,
    CANVAS_HEIGHT: 600,
    GRAVITY: 0.5,
    JUMP_STRENGTH: -12,
    MOVE_SPEED: 5,
    GROUND_Y: 500,
    COLORS: {
        EGG_BODY: '#FFFACD',
        EGG_OUTLINE: '#FFD700',
        OBSTACLE: '#FF6B6B',
        STAR: '#FFD700',
        PLATFORM: '#8B4513'
    }
};

// 蛋仔角色类
class Egg {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 40;
        this.height = 50;
        this.velocityX = 0;
        this.velocityY = 0;
        this.isJumping = false;
        this.color = CONFIG.COLORS.EGG_BODY;
        this.eyeAnimation = 0;
        this.bounceAnimation = 0;
        this.direction = 1; // 1为右，-1为左
        this.invulnerable = false;
        this.invulnerableTime = 0;
    }

    update() {
        // 应用重力
        this.velocityY += CONFIG.GRAVITY;
        
        // 更新位置
        this.x += this.velocityX;
        this.y += this.velocityY;
        
        // 地面碰撞检测
        if (this.y + this.height >= CONFIG.GROUND_Y) {
            this.y = CONFIG.GROUND_Y - this.height;
            this.velocityY = 0;
            this.isJumping = false;
        }
        
        // 边界检测
        if (this.x < 0) this.x = 0;
        if (this.x + this.width > CONFIG.CANVAS_WIDTH) {
            this.x = CONFIG.CANVAS_WIDTH - this.width;
        }
        
        // 动画更新
        this.eyeAnimation += 0.1;
        this.bounceAnimation += 0.15;
        
        // 减速
        this.velocityX *= 0.9;
        
        // 无敌时间更新
        if (this.invulnerable) {
            this.invulnerableTime--;
            if (this.invulnerableTime <= 0) {
                this.invulnerable = false;
            }
        }
    }

    jump() {
        if (!this.isJumping) {
            this.velocityY = CONFIG.JUMP_STRENGTH;
            this.isJumping = true;
        }
    }

    moveLeft() {
        this.velocityX = -CONFIG.MOVE_SPEED;
        this.direction = -1;
    }

    moveRight() {
        this.velocityX = CONFIG.MOVE_SPEED;
        this.direction = 1;
    }

    draw(ctx) {
        ctx.save();
        
        // 无敌闪烁效果
        if (this.invulnerable && Math.floor(this.invulnerableTime / 5) % 2 === 0) {
            ctx.globalAlpha = 0.5;
        }
        
        // 蛋仔身体
        ctx.fillStyle = this.color;
        ctx.strokeStyle = CONFIG.COLORS.EGG_OUTLINE;
        ctx.lineWidth = 3;
        
        // 弹跳效果
        const bounceY = Math.sin(this.bounceAnimation) * 2;
        
        // 绘制椭圆形身体
        ctx.beginPath();
        ctx.ellipse(this.x + this.width/2, this.y + this.height/2 + bounceY, 
                   this.width/2, this.height/2, 0, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();
        
        // 绘制眼睛
        this.drawEyes(ctx, bounceY);
        
        // 绘制嘴巴
        this.drawMouth(ctx, bounceY);
        
        // 绘制腮红
        this.drawBlush(ctx, bounceY);
        
        ctx.restore();
    }

    drawEyes(ctx, bounceY) {
        const eyeY = this.y + this.height/3 + bounceY;
        const eyeSize = 4;
        const eyeSpacing = 12;
        
        // 左眼
        ctx.fillStyle = '#000';
        ctx.beginPath();
        ctx.arc(this.x + this.width/2 - eyeSpacing, eyeY, eyeSize, 0, Math.PI * 2);
        ctx.fill();
        
        // 右眼
        ctx.beginPath();
        ctx.arc(this.x + this.width/2 + eyeSpacing, eyeY, eyeSize, 0, Math.PI * 2);
        ctx.fill();
        
        // 眼睛高光
        ctx.fillStyle = '#FFF';
        ctx.beginPath();
        ctx.arc(this.x + this.width/2 - eyeSpacing + 1, eyeY - 1, 1.5, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.beginPath();
        ctx.arc(this.x + this.width/2 + eyeSpacing + 1, eyeY - 1, 1.5, 0, Math.PI * 2);
        ctx.fill();
    }

    drawMouth(ctx, bounceY) {
        const mouthY = this.y + this.height/2 + bounceY;
        
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, mouthY, 8, 0.2 * Math.PI, 0.8 * Math.PI);
        ctx.stroke();
    }

    drawBlush(ctx, bounceY) {
        const blushY = this.y + this.height/2 + 5 + bounceY;
        
        ctx.fillStyle = 'rgba(255, 192, 203, 0.6)';
        
        // 左腮红
        ctx.beginPath();
        ctx.ellipse(this.x + 10, blushY, 6, 4, 0, 0, Math.PI * 2);
        ctx.fill();
        
        // 右腮红
        ctx.beginPath();
        ctx.ellipse(this.x + this.width - 10, blushY, 6, 4, 0, 0, Math.PI * 2);
        ctx.fill();
    }

    getBounds() {
        return {
            x: this.x,
            y: this.y,
            width: this.width,
            height: this.height
        };
    }

    takeDamage() {
        if (!this.invulnerable) {
            this.invulnerable = true;
            this.invulnerableTime = 120; // 2秒无敌时间
            return true;
        }
        return false;
    }
}

// 障碍物类
class Obstacle {
    constructor(x, y, width, height, speed = 0) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.speed = speed;
        this.color = CONFIG.COLORS.OBSTACLE;
        this.rotation = 0;
    }

    update() {
        this.x += this.speed;
        this.rotation += 0.05;
    }

    draw(ctx) {
        ctx.save();
        ctx.translate(this.x + this.width/2, this.y + this.height/2);
        ctx.rotate(this.rotation);
        
        ctx.fillStyle = this.color;
        ctx.fillRect(-this.width/2, -this.height/2, this.width, this.height);
        
        // 危险标记
        ctx.fillStyle = '#FFF';
        ctx.font = 'bold 20px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('!', 0, 0);
        
        ctx.restore();
    }

    isOffScreen() {
        return this.x + this.width < 0 || this.x > CONFIG.CANVAS_WIDTH;
    }

    getBounds() {
        return {
            x: this.x,
            y: this.y,
            width: this.width,
            height: this.height
        };
    }
}

// 星星收集物类
class Star {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.size = 20;
        this.collected = false;
        this.rotation = 0;
        this.floatY = 0;
    }

    update() {
        this.rotation += 0.05;
        this.floatY = Math.sin(this.rotation) * 5;
    }

    draw(ctx) {
        if (this.collected) return;
        
        ctx.save();
        ctx.translate(this.x, this.y + this.floatY);
        ctx.rotate(this.rotation);
        
        // 绘制星星
        ctx.fillStyle = CONFIG.COLORS.STAR;
        ctx.strokeStyle = '#FFA500';
        ctx.lineWidth = 2;
        
        ctx.beginPath();
        for (let i = 0; i < 5; i++) {
            const angle = (i * 2 * Math.PI / 5) - Math.PI / 2;
            const x = Math.cos(angle) * this.size;
            const y = Math.sin(angle) * this.size;
            
            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
            
            const innerAngle = angle + Math.PI / 5;
            const innerX = Math.cos(innerAngle) * (this.size / 2);
            const innerY = Math.sin(innerAngle) * (this.size / 2);
            ctx.lineTo(innerX, innerY);
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        
        ctx.restore();
    }

    getBounds() {
        return {
            x: this.x - this.size,
            y: this.y - this.size,
            width: this.size * 2,
            height: this.size * 2
        };
    }
}

// 平台类
class Platform {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = CONFIG.COLORS.PLATFORM;
    }

    draw(ctx) {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        
        // 平台纹理
        ctx.strokeStyle = '#654321';
        ctx.lineWidth = 1;
        for (let i = 0; i < this.width; i += 10) {
            ctx.beginPath();
            ctx.moveTo(this.x + i, this.y);
            ctx.lineTo(this.x + i, this.y + this.height);
            ctx.stroke();
        }
    }

    getBounds() {
        return {
            x: this.x,
            y: this.y,
            width: this.width,
            height: this.height
        };
    }
}

// 游戏主类
class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.egg = null;
        this.obstacles = [];
        this.stars = [];
        this.platforms = [];
        this.score = 0;
        this.lives = 3;
        this.level = 1;
        this.gameState = 'menu'; // menu, playing, paused, gameover
        this.keys = {};
        this.lastTime = 0;
        this.obstacleTimer = 0;
        this.starTimer = 0;
        
        this.init();
    }

    init() {
        this.egg = new Egg(100, 300);
        this.setupEventListeners();
        this.createLevel(this.level);
        this.updateUI();
        this.gameLoop();
    }

    setupEventListeners() {
        // 键盘事件
        window.addEventListener('keydown', (e) => {
            this.keys[e.key] = true;
            
            if (e.key === 'Enter' && this.gameState === 'menu') {
                this.startGame();
            }
        });

        window.addEventListener('keyup', (e) => {
            this.keys[e.key] = false;
        });

        // 按钮事件
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
        document.getElementById('restartBtn').addEventListener('click', () => this.restartGame());
    }

    createLevel(levelNum) {
        // 清空现有元素
        this.obstacles = [];
        this.stars = [];
        this.platforms = [];
        
        // 创建平台
        this.platforms.push(new Platform(200, 400, 100, 20));
        this.platforms.push(new Platform(400, 350, 100, 20));
        this.platforms.push(new Platform(600, 300, 100, 20));
        
        // 根据关卡创建初始星星
        for (let i = 0; i < 5; i++) {
            this.stars.push(new Star(
                200 + i * 120,
                200 + Math.random() * 200
            ));
        }
    }

    startGame() {
        this.gameState = 'playing';
        this.score = 0;
        this.lives = 3;
        this.level = 1;
        this.egg = new Egg(100, 300);
        this.createLevel(this.level);
        this.updateUI();
    }

    togglePause() {
        if (this.gameState === 'playing') {
            this.gameState = 'paused';
        } else if (this.gameState === 'paused') {
            this.gameState = 'playing';
        }
    }

    restartGame() {
        this.startGame();
    }

    gameOver() {
        this.gameState = 'gameover';
        this.showGameOver();
    }

    showGameOver() {
        const overlay = document.createElement('div');
        overlay.className = 'game-over-overlay';
        overlay.innerHTML = `
            <div class="game-over-content">
                <h2>游戏结束!</h2>
                <div class="final-score">最终得分: ${this.score}</div>
                <button onclick="location.reload()">重新开始</button>
            </div>
        `;
        document.body.appendChild(overlay);
    }

    handleInput() {
        if (this.gameState !== 'playing') return;
        
        if (this.keys['ArrowLeft']) {
            this.egg.moveLeft();
        }
        if (this.keys['ArrowRight']) {
            this.egg.moveRight();
        }
        if (this.keys['ArrowUp']) {
            this.egg.jump();
        }
    }

    spawnObstacle() {
        this.obstacleTimer++;
        if (this.obstacleTimer > 60 + Math.random() * 60) { // 1-2秒生成一个
            this.obstacles.push(new Obstacle(
                CONFIG.CANVAS_WIDTH,
                CONFIG.GROUND_Y - 40,
                30,
                40,
                -2 - this.level * 0.5
            ));
            this.obstacleTimer = 0;
        }
    }

    spawnStar() {
        this.starTimer++;
        if (this.starTimer > 120 && this.stars.filter(s => !s.collected).length < 3) {
            this.stars.push(new Star(
                CONFIG.CANVAS_WIDTH,
                100 + Math.random() * 300
            ));
            this.starTimer = 0;
        }
    }

    checkCollisions() {
        // 蛋仔与障碍物碰撞
        for (let obstacle of this.obstacles) {
            if (this.checkCollision(this.egg.getBounds(), obstacle.getBounds())) {
                if (this.egg.takeDamage()) {
                    this.lives--;
                    this.updateUI();
                    
                    if (this.lives <= 0) {
                        this.gameOver();
                    }
                }
            }
        }
        
        // 蛋仔与星星碰撞
        for (let star of this.stars) {
            if (!star.collected && this.checkCollision(this.egg.getBounds(), star.getBounds())) {
                star.collected = true;
                this.score += 100;
                this.updateUI();
                
                // 检查是否升级
                if (this.score >= this.level * 500) {
                    this.levelUp();
                }
            }
        }
        
        // 蛋仔与平台碰撞
        for (let platform of this.platforms) {
            if (this.checkCollision(this.egg.getBounds(), platform.getBounds())) {
                // 简单的平台碰撞处理
                if (this.egg.velocityY > 0 && this.egg.y < platform.y) {
                    this.egg.y = platform.y - this.egg.height;
                    this.egg.velocityY = 0;
                    this.egg.isJumping = false;
                }
            }
        }
    }

    checkCollision(rect1, rect2) {
        return rect1.x < rect2.x + rect2.width &&
               rect1.x + rect1.width > rect2.x &&
               rect1.y < rect2.y + rect2.height &&
               rect1.y + rect1.height > rect2.y;
    }

    levelUp() {
        this.level++;
        this.createLevel(this.level);
        this.updateUI();
    }

    updateUI() {
        document.getElementById('score').textContent = `得分: ${this.score}`;
        document.getElementById('level').textContent = `关卡: ${this.level}`;
        
        let livesText = '生命: ';
        for (let i = 0; i < this.lives; i++) {
            livesText += '❤️';
        }
        document.getElementById('lives').textContent = livesText;
    }

    update() {
        if (this.gameState !== 'playing') return;
        
        this.handleInput();
        
        // 更新蛋仔
        this.egg.update();
        
        // 更新障碍物
        this.obstacles = this.obstacles.filter(obstacle => {
            obstacle.update();
            return !obstacle.isOffScreen();
        });
        
        // 更新星星
        this.stars.forEach(star => star.update());
        
        // 生成新的游戏元素
        this.spawnObstacle();
        this.spawnStar();
        
        // 碰撞检测
        this.checkCollisions();
    }

    draw() {
        // 清空画布
        this.ctx.clearRect(0, 0, CONFIG.CANVAS_WIDTH, CONFIG.CANVAS_HEIGHT);
        
        // 绘制背景
        this.drawBackground();
        
        // 绘制平台
        this.platforms.forEach(platform => platform.draw(this.ctx));
        
        // 绘制星星
        this.stars.forEach(star => star.draw(this.ctx));
        
        // 绘制障碍物
        this.obstacles.forEach(obstacle => obstacle.draw(this.ctx));
        
        // 绘制蛋仔
        if (this.egg) {
            this.egg.draw(this.ctx);
        }
        
        // 绘制游戏状态信息
        if (this.gameState === 'paused') {
            this.drawPaused();
        } else if (this.gameState === 'menu') {
            this.drawMenu();
        }
    }

    drawBackground() {
        // 天空渐变
        const gradient = this.ctx.createLinearGradient(0, 0, 0, CONFIG.CANVAS_HEIGHT);
        gradient.addColorStop(0, '#87CEEB');
        gradient.addColorStop(1, '#98FB98');
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, CONFIG.CANVAS_WIDTH, CONFIG.CANVAS_HEIGHT);
        
        // 绘制地面
        this.ctx.fillStyle = '#8B7355';
        this.ctx.fillRect(0, CONFIG.GROUND_Y, CONFIG.CANVAS_WIDTH, CONFIG.CANVAS_HEIGHT - CONFIG.GROUND_Y);
        
        // 绘制草地
        this.ctx.fillStyle = '#90EE90';
        this.ctx.fillRect(0, CONFIG.GROUND_Y, CONFIG.CANVAS_WIDTH, 10);
        
        // 绘制云朵
        this.drawClouds();
    }

    drawClouds() {
        const clouds = [
            { x: 100, y: 80, size: 30 },
            { x: 300, y: 120, size: 25 },
            { x: 500, y: 60, size: 35 },
            { x: 700, y: 100, size: 28 }
        ];
        
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        clouds.forEach(cloud => {
            this.ctx.beginPath();
            this.ctx.arc(cloud.x, cloud.y, cloud.size, 0, Math.PI * 2);
            this.ctx.arc(cloud.x + cloud.size, cloud.y, cloud.size * 0.8, 0, Math.PI * 2);
            this.ctx.arc(cloud.x - cloud.size, cloud.y, cloud.size * 0.8, 0, Math.PI * 2);
            this.ctx.fill();
        });
    }

    drawMenu() {
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        this.ctx.fillRect(0, 0, CONFIG.CANVAS_WIDTH, CONFIG.CANVAS_HEIGHT);
        
        this.ctx.fillStyle = '#FFF';
        this.ctx.font = 'bold 48px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText('蛋仔派对', CONFIG.CANVAS_WIDTH / 2, 200);
        
        this.ctx.font = '24px Arial';
        this.ctx.fillText('按 Enter 开始游戏', CONFIG.CANVAS_WIDTH / 2, 300);
        
        this.ctx.font = '18px Arial';
        this.ctx.fillText('使用 ← → 控制移动，↑ 跳跃', CONFIG.CANVAS_WIDTH / 2, 350);
        this.ctx.fillText('躲避障碍物，收集星星！', CONFIG.CANVAS_WIDTH / 2, 380);
    }

    drawPaused() {
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        this.ctx.fillRect(0, 0, CONFIG.CANVAS_WIDTH, CONFIG.CANVAS_HEIGHT);
        
        this.ctx.fillStyle = '#FFF';
        this.ctx.font = 'bold 36px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText('游戏暂停', CONFIG.CANVAS_WIDTH / 2, CONFIG.CANVAS_HEIGHT / 2);
    }

    gameLoop(currentTime = 0) {
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        this.update();
        this.draw();
        
        requestAnimationFrame((time) => this.gameLoop(time));
    }
}

// 启动游戏
window.addEventListener('load', () => {
    const game = new Game();
});